function pfn(filename, bspec)
% pfn: print the file details. 2 usages:
%   1) pfn<cr> lists the currenty open acquisition file.
%   2) pfn filename lists index of disk file.
%
% opens the file and loades the index...
% and lists contents to matlab window
% pfn is derived from lif, but lists more information
%
% revised 30 July 04 to allow printing of the text rather than the window.
%

global LASTPATH
global CONTROL

persistent list
persistent truefile

if(nargin == 0)
    filename= '';
    bspec = 0;
end;

cmds = {'open', 'print', 'close'};
switch(filename)
    case 'open'
        [drive, path, ext] = getdriveext;
        lookpath=strcat(path, ext);
        [filename, path] = uigetfile(lookpath, 'View Info from Data File');
        if(~ischar(filename))
            QueMessage(sprintf('Unable to access file? %s - %s', path, filename));
            result = 1;
            return;
        end
        setdriveext('path', path);
        LASTPATH = path;
        lookpath = path;
        truefile = strcat(path, filename);
        [path, name, ext, ver] = fileparts(truefile);
        if(~strcmp(ext, '.mat'))
            notefile = fullfile(path, [name, '.not']);
        else
            notefile = fullfile(path, [name, ext]);
        end;
        pfn(notefile);
    case 'edit'
        tdir = tempdir;
        nf=tempname;
        hf=fopen(nf, 'w');
        if(isempty(hf))
            return;
        end;
        try
            for i = 1:length(list)
                li=char(list{i});
            fprintf(hf, '%s\r\n', li);
            end;
            fclose(hf);
            system(sprintf('/Applications/textedit %s', nf));
        catch
            fprintf(1, '? cant put file to notepad?\n');
        end
        
    case 'close'
        hpf = findobj('Tag', 'pnotefile'); % see if one exists...
        if(~isempty(hpf))
            close(hpf);
        end;
    case 'print' % with mods to send data to HP PCl printer....
        esc = 27;
        if(~isempty(list))
            hf = fopen('tempnote.txt', 'w');
            fprintf(hf, '%cE%c(10U%c(s0p12h10v0s0b2T', esc, esc, esc);
            for i = 1:length(list)
                fprintf(hf, '%s\r\n', char(list{i}));
            end;
            fclose(hf);
            system('lpr -lp tempnote.txt');
        end;
        
                
    otherwise % behave as used to
        
        
        if(nargin < 1)
            sf = getmainselection;
            if(length(sf) > 1)
                sf = sf(1);
            end;
            filename = [CONTROL(sf).path CONTROL(sf).filename];
        end;
        if(nargin < 2)
            bspec = []; % block specification (to pick certain block types)
        else
            if(~strmatch(lower(bspec), {'data', 'sf', 'df', 'note', 'header', 'html'}, 'exact'))
                fprintf(2, 'block spec type %s not recognized\n', bspec);
                return;
            end;
        end;
        if(strmatch(lower(bspec), 'html'))
            bspec = []; % remove the specification
            html_flag = 0;
        else
            html_flag = 0;
        end;
        
        
        [p f e] = fileparts(filename);
        
        if(strcmp(e, '.not')) % old datac notefile - put up the window with the raw notefile in it.
            fid = fopen(filename, 'rt');
            if (fid == -1)
                QueMessage(sprintf('%s not found.', filename));
                return
            end
            disp_list = {};
            while (~feof(fid))
                new_line = fgetl(fid);
                if (new_line == -1)
                    break
                else
                    disp_list{end + 1} = new_line;
                end
            end
            if(~isempty(disp_list))
                % create a new figure window for the listing (allows us to generate a printable list)
                hpf = findobj('Tag', 'pnotefile'); % see if one exists...
                if(isempty(hpf))
                    hpf = figure( ...
                        'name', 'Printable Notefile 7-30-04', ...
                        'Units', 'normalized', ...
                        'Position', [0.1 0.1 0.8 0.8], ...
                        'BackingStore', 'on', ...
                        'NumberTitle', 'off', ...
                        'Menubar', 'none', ...
                        'Tag','pnotefile');
                end;
                figure(hpf);
                clf;
                f = uimenu('Label', '&File', 'Position', 1);
                uimenu(f, 'Label', '&Open', 'Callback', 'datac NoteInFile');
                uimenu(f, 'Label', '&Print', 'Callback', 'pfn(''print'');');
                uimenu(f, 'Label', '&Edit', 'Callback', 'pfn(''edit'');');
                uimenu(f, 'Label', '&Exit', 'Callback', 'pfn(''close''));');
                
                hlist = uicontrol('Parent',hpf, ...
                    'Units','normalized', ...
                    'BackgroundColor','white', ...
                    'ForegroundColor', 'black', ...
                    'ListboxTop',1, ...
                    'Position', [0.02 0.02 0.98 0.98], ...
                    'HorizontalAlignment','left', ...
                    'String','', ...
                    'Style','ListBox', ...
                    'FontSize', 8, ...
                    'FontName', 'FixedWidth', ...
                    'Tag','TheList');
            end;
            set(hlist, 'String', disp_list);
            return;
        end;  
        
        
        % display mat files.
        
        if(isempty(filename))
            if(exist('INDEX.mat') ~= 2)
                [filename, pathname] = uigetfile('*.mat', 'File for listing?');
                if(filename == 0)
                    return;
                end;
                if(html_flag)
                    [p f e] = fileparts(filename);
                    htmlfile = fullfile(pathname, [f '.html']); % make an html filename
                end;
            else
                filename = 'INDEX';
            end;
            filename = [pathname, filename];   
        end;
        v=[];
        if(exist(filename) == 2)
            v = load(filename, 'Index');
        else
            fprintf('File %s not found?\n', filename);
            return;
        end;
        if(isempty(fieldnames(v)))
            v=load(filename, 'INDEX'); % maybe file is not closed
            if(isempty(fieldnames(v)))
                fprintf(2, 'lif: No index associated with file %s\n', filename);
                return;
            end;
        end;
        
        % create a new figure window for the listing (allows us to generate a printable list)
        hpf = findobj('Tag', 'pnotefile'); % see if one exists...
        if(isempty(hpf))
            hpf = figure( ...
                'name', 'Printable Notefile', ...
                'Units', 'pixels', ...
                'Position', [10 10 600 700], ...
                'BackingStore', 'on', ...
                'NumberTitle', 'off', ...
                'Menubar', 'none', ...
                'Tag','pnotefile');
        end;
        figure(hpf);
        clf;
            f = uimenu('Label', '&File', 'Position', 1);
                uimenu(f, 'Label', '&Open', 'Callback', 'datac NoteInFile');
                 uimenu(f, 'Label', '&Print', 'Callback', 'pfn(''print'');');
               uimenu(f, 'Label', '&Edit', 'Callback', 'pfn edit;');
                uimenu(f, 'Label', '&Close', 'Callback', 'pfn close;');
            hlist = uicontrol('Parent',hpf, ...
            'Units','normalized', ...
            'BackgroundColor','white', ...
            'ForegroundColor', 'black', ...
            'ListboxTop',1, ...
            'Position', [0.02 0.02 0.98 0.98], ...
            'HorizontalAlignment','left', ...
            'String','', ...
            'Style','ListBox', ...
            'FontSize', 10, ...
            'FontName', 'FixedWidth', ...
            'Tag','TheList');
        
        divider = sprintf('---------------------------------------------------------------------------');
        element = fieldnames(v);
        INDEX = eval(['v.' char(element)]);
        list = {};
        list = cellcat(list, sprintf('File: %s', filename));
        load(filename, 'HFILE'); % get the header information.
        list = cellcat(list, sprintf('Signature: %s', char(HFILE.Signature.v)));
        list = cellcat(list, sprintf('Species: %s  Age: %s Wt: %s  Sex: %s', char(HFILE.Species.v), ...
            char(HFILE.Age.v), char(HFILE.Weight.v), char(HFILE.Sex.v)));
        c=char(HFILE.Experiment.v);
        list = cellcat(list, 'Experiment:');
        for j = 1:size(c,1)
            if(length(c(j,:)) > 0 & ~all(isspace(c(j,:))))
                o = linebreak(c(j,:));
                lend = find(o == 13);
                if(isempty(lend))
                    list = cellcat(list, sprintf('   %s', o));
                else
                    k = 1;
                    for i = 1:length(lend)
                        list = cellcat(list, sprintf('    %s', o(k:lend(i)-1)));
                        k = lend(i)+1;
                    end;
                end;
                
                %      list = cellcat(list, sprintf('%s', c(j,:)));
            end;
        end;
        list = cellcat(list, divider);
        
        list = cellcat(list, sprintf('Index for File: %s  ', filename));
        s = length(INDEX);
        list = cellcat(list, sprintf('    Date      Time     Block   Rec         Type         Info          Name'));    
        list = cellcat(list, sprintf('---------------------------------------------------------------------------'));
        for i = 1:s
            if(isempty(bspec))
                list = cellcat(list, sprintf('%8s  %8s  %4d  %4d  %12s  %12s  %12s', ...
                    INDEX(i).date, INDEX(i).time, INDEX(i).block, INDEX(i).record, INDEX(i).type, INDEX(i).type2, INDEX(i).MatName));
            else
                if(strmatch(lower(bspec), lower(INDEX(i).type), 'exact'))
                    list = cellcat(list, sprintf('%8s  %8s  %4d  %4d  %12s  %12s  %12s', INDEX(i).date, INDEX(i).time, INDEX(i).block, INDEX(i).record, INDEX(i).type, INDEX(i).type2, INDEX(i).MatName));
                end;
            end;
            
        end;
        list = cellcat(list, sprintf('---------------------------------------------------------------------------'));
        
        data_blks = strmatch('DATA', char(INDEX.type), 'exact');
        notes = strmatch('NOTE', char(INDEX.type), 'exact');
        note_blks = [INDEX(notes).block]; % identify these by the BLOCK number itself...
        data_blks = union(data_blks, notes); % identify indices to all blocks we need to access
        % now for each element of the input index, print some information
        done_blk = [];
        for indxi = 1:length(data_blks) % look for the data in all the blocks (it doesn't hurt to search)
            ind = data_blks(indxi);
            %   fprintf(1, '%d: %d -- %d\n', indxi, INDEX(ind-1).record, INDEX(ind).record);
            this_block = INDEX(ind).block;
            dblk = [];
            if(~isempty(done_blk)) % just prevent warning message
                dblk = find(this_block == done_blk); % check to see if we have already processed block number (union may return multiple indices for same block)
            end;
            if(isempty(dblk))
                done_blk = [done_blk this_block]; % add (provisionally) finished block to the list
                this_time = INDEX(ind).time;
                list = cellcat(list, '****************************');
                binfo = sprintf('BLOCK: %d started at %8s, contains', ...
                    this_block, this_time);
                [sfile, df, notes] = block_info(filename, this_block);
                %      if((INDEX(ind-1).record - INDEX(ind).record) == 0)
                %        fprintf(1, ' No records\n');
                %    else
                list = cellcat(list, sprintf('%s records: %d-%d', binfo, INDEX(ind-1).record, INDEX(ind).record));
                %   end;
                
                if(~isempty(df) & ~ isempty(sfile))
                    list = cellcat(list, '----------------------------');
                    list = cellcat(list, 'Acquisition Parameters                 Stimulus Parameters');
                    if(length(df.Filename.v) == 0 | isempty(df.Filename.v) | all(isspace(df.Filename.v)))
                        fnm = '**auto**';
                    else
                        fnm = df.Filename.v;
                    end;
                    list = cellcat(list, sprintf('File: %-24s         File: %-24s', ...
                        fnm, sfile.Name.v));
                    list = cellcat(list, sprintf('Rate (us): %6.2f   Points: %5d      Cycle (s): %.1f   Rpt: %d   Prot-Rpt: %d',...
                        df.Sample_Rate.v, df.Points.v, sfile.Cycle.v, sfile.Repeats.v, sfile.Stim_Repeat.v));
                    chl = 'Channels [';
                    for ii = 1: length(df.Channels.v)
                        chl = strcat(chl, sprintf(' %2d ', df.Channels.v(ii)));
                    end;
                    chl = strcat(chl, ']');
                    for ii = length(df.Channels.v):8
                        chl = strcat(chl, '    ');
                    end;
                    list = cellcat(list, sprintf('%s         SeqPar: %s    Sequence: %s', ...
                        chl, sfile.SeqParList.v, sfile.Sequence.v));
                    
                    gl = 'Gain     [';
                    for ii = 1: length(df.Amplifier_Gain.v)
                        gl = sprintf('%s%4.1f', gl, df.Amplifier_Gain.v(ii));
                    end;
                    gl = strcat(gl, ']');
                    for ii=length(df.Amplifier_Gain.v):8
                        gl = strcat(gl, '    ');
                    end;
                    
                    si = sfile.Superimpose.v;
                    if(length(si) == 0)
                        si = '**none**';
                    end;
                    ac=sfile.Addchannel.v;
                    if(length(ac) == 0)
                        ac = '**none**';
                    end;
                    list = cellcat(list, sprintf('%s Superimpose: %s   AddChannel: %s', ...
                        gl, sfile.Superimpose.v, sfile.Addchannel.v));
                    list = cellcat(list, '----------------------');
                end;
                
                if(~isempty(notes))
                    for i = 1:length(notes)  % notes{1}.v
                        c=char(notes{i}.v);
                        if(strmatch(fieldnames(notes{1}), 't'))
                            list = cellcat(list, sprintf('Note (%2d:%2d:%2.0f):', ...
                                notes{1}.t(4), notes{1}.t(5), notes{1}.t(6)));
                        end;
                        for j = 1:size(c,1)
                            if(length(c(j,:)) > 0 & ~all(isspace(c(j,:))))
                                if(j == 1)
                                    o = linebreak(c(j,:));
                                    lend = find(o == 13);
                                    if(isempty(lend))
                                        list = cellcat(list, sprintf('Note:  %s', o));
                                    else
                                        k = 1;
                                        for i = 1:length(lend)
                                            list = cellcat(list, sprintf('      %s', o(k:lend(i)-1)));
                                            k = lend(i)+1;
                                        end;
                                    end;
                                    
                                else
                                    o = linebreak(c(j,:));
                                    lend = find(o == 13);
                                    if(isempty(lend))
                                        list = cellcat(list, sprintf('       %s', o));
                                    else
                                        k = 1;
                                        for i = 1:length(lend)
                                            list = cellcat(list, sprintf('      %s', o(k:lend(i)-1)));
                                            k = lend(i)+1;
                                        end;
                                    end;
                                end;                     
                            end;
                        end;
                        list = cellcat(list, divider);
                    end;
                end;         
            end;   
        end;
        
        
        set(hlist, 'String', list);
        
        if(html_flag)
            htmlfile
            hhtm = fopen(htmlfile, 'w'); % overwrites previous by this name.
            fprintf(hhtm, '<html>\n<head>\n<title>Notefile for %s</title>\n', filename);
            fprintf(hhtm, '<meta http-equiv=\"Content-Type\" content=\"text/html;charset=iso-8859-1\">');
            fprintf(hhtm, '</head><body><a NAME=\"Top\"></a><font size = "3"><pre>\n');
            noteflag = 0;
            for i = 1: length(list)
                if(findstr(list{i}, 'DATA'))
                    dnp = findstr(list{i}, 'db_');
                    id = sscanf(list{i}(dnp:end), 'db_%d'); % get the number, create a link to the tag
                    fprintf(hhtm, '<a href=\"#blk_%d\"><b>%s</b></a><br>', id, list{i});
                elseif (findstr(list{i}, 'BLOCK:'))
                    dnp = findstr(list{i}, 'BLOCK:'); % create the block tag here too (target).
                    id = sscanf(list{i}(dnp:dnp+9), 'BLOCK: %d');
                    fprintf(hhtm, '<a NAME=\"blk_%d\"><b>%s</b></a> <a href=\"#Top\">^</a><br>', id, list{i});
                    
                elseif(~isempty(findstr(list{i}, '********'))) % turn off noteflag stuff
                    noteflag = 0;
                    fprintf(hhtm, '<font color=#000000>%s<br>', list{i});
                elseif (~isempty(findstr(list{i}, 'Note:'))) % when in a note, italic/bold.
                    fprintf(hhtm, '<font color=#0000ff><i>%s</i><br>', list{i});
                    noteflag = 1;
                else
                    fprintf(hhtm, '%s<br>', list{i});
                end;
            end;
            
            fprintf(hhtm, '</font></pre></body>\n</html>');
            fclose(hhtm);
            % launch browser to read the file...
            dos (sprintf('c:\\progra~1\\netscape\\communicator\\program\\netscape.exe %s &', ...
                htmlfile));
        end;
end; % of the otherwise in the switch case

return;


function [sfile, df, notes] = block_info(filename, wblk)

sfile=[];
df=[];
notes={};
sfc = sprintf('sf%d', wblk);
sfile = load(filename, sfc); % read the stim block
if(~isempty(fieldnames(sfile)))
    sfile = eval(['sfile.' sfc]);
    dfc = sprintf('df%d', wblk);
    df = load(filename, dfc); % read the data block
    df = eval(['df.' dfc]);
else
    sfile = [];
    df = [];
end;
nfc = sprintf('Note%d_*', wblk);
nf = load(filename, nfc);
if(~isempty(fieldnames(nf)))
    fn = fieldnames(nf);
    for i = 1:length(fn)
        notes{i}.v = eval(['nf.' fn{i} '.v']);
        %      notes{i}.t = eval(['nf.' fn{i} '.t']);
    end;
end;
return;

function [o] = cellcat(in, string)
o = in;
p = length(in) + 1;
o{p} = string;
return;

